package netty.zerocopy;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * Created with IntelliJ IDEA.
 * User: SuQiEr
 * Date:2017/11/4 0004
 * Time: 下午 4:29
 * To change this template use File | Settings | File Templates.
 */
public class NewIOServer {
    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel =  ServerSocketChannel.open();
        ServerSocket serverSocket = serverSocketChannel.socket();
        serverSocket.setReuseAddress(true);
        serverSocket.bind(new InetSocketAddress(8080));
        ByteBuffer bb = ByteBuffer.allocate(1024);
        while (true){
            SocketChannel socketChannel = serverSocketChannel.accept();
            socketChannel.configureBlocking(true);
            int readCount = 0;
            while (readCount != -1){
                try{
                    readCount =   socketChannel.read(bb);
                    System.out.println("读取文件大小:"+readCount);
                    bb.rewind();
                    bb.put("服务端".getBytes("UTF-8"));
                    socketChannel.write(bb);
                }catch (Exception ex){
                    System.out.println("异常");
                }

            }
            System.out.println("文件读取完成");
        }


    }
}
